<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
  <title>棋牌选桌模拟</title>
  <style>
    /* 模拟桌子的样式 */
    .real-table {
      position: relative;
      width: 240px;
      height: 240px;
      background: url('https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80') no-repeat center center;
      background-size: cover;
      border-radius: 10px;
      box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
      margin: 20px;
      transition: all 0.3s ease;
    }

    .real-table:hover {
      transform: scale(1.05);
    }

    /* 模拟椅子的样式 */
    .chair {
      position: absolute;
      width: 60px;
      height: 60px;
      background: url('https://images.unsplash.com/photo-1574171406420-6979d8a97f49?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80') no-repeat center center;
      background-size: cover;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .chair:hover {
      transform: scale(1.1);
    }

    /* 调整椅子的位置 */
    .chair.top {
      top: -30px;
      left: 50%;
      transform: translateX(-50%);
    }

    .chair.right {
      top: 50%;
      right: -30px;
      transform: translateY(-50%);
    }

    .chair.bottom {
      bottom: -30px;
      left: 50%;
      transform: translateX(-50%);
    }

    .chair.left {
      top: 50%;
      left: -30px;
      transform: translateY(-50%);
    }

    /* 座位样式 */
    .seat {
      width: 60px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
    }

    .seat img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
    }

    .seat .player-name {
      position: absolute;
      bottom: -20px;
      left: 50%;
      transform: translateX(-50%);
      font-size: 12px;
      color: white;
      text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
    }

    /* 游戏开始提示样式 */
    .game-started {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: red;
      font-size: 24px;
      font-weight: bold;
      text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
    }
  </style>
</head>

<body class="bg-gray-100 font-sans">
  <div class="container mx-auto p-8">
    <h1 class="text-3xl font-bold text-center mb-8">棋牌选桌</h1>
    <div id="tables" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-24">
      <!-- 动态生成牌桌 -->
    </div>
    <div class="mt-8 text-center">
      <input type="text" id="player-name" placeholder="请输入玩家姓名" class="border border-gray-300 p-2 rounded-md mr-2">
      <button id="login-button" class="bg-blue-500 text-white p-2 rounded-md hover:bg-blue-600">登录</button>
    </div>
  </div>

  <script>
    const numTables = 6;
    const seatsPerTable = 4;
    const socket = new WebSocket('ws://localhost:3000');

    function renderTables(tables) {
      const tablesDiv = document.getElementById('tables');
      tablesDiv.innerHTML = '';
      tables.forEach((table, tableIndex) => {
        const tableDiv = document.createElement('div');
        tableDiv.classList.add('real-table');

        const seatPositions = [
          { class: 'top' },
          { class: 'right' },
          { class: 'bottom' },
          { class: 'left' }
        ];

        table.seats.forEach((player, seatIndex) => {
          const chairDiv = document.createElement('div');
          chairDiv.classList.add('chair', seatPositions[seatIndex].class);
          const seatDiv = document.createElement('div');
          seatDiv.classList.add('seat');
          if (player) {
            const img = document.createElement('img');
            if (player.avatar) {
              img.src = player.avatar;
            } else {
              img.src = 'https://picsum.photos/64/64';
            }
            seatDiv.appendChild(img);
            const playerNameDiv = document.createElement('div');
            playerNameDiv.classList.add('player-name');
            playerNameDiv.textContent = player.name;
            seatDiv.appendChild(playerNameDiv);
          } else {
            seatDiv.textContent = '空位';
            seatDiv.addEventListener('click', () => joinSeat(tableIndex, seatIndex));
          }
          chairDiv.appendChild(seatDiv);
          tableDiv.appendChild(chairDiv);
        });

        if (table.gameStarted) {
          const gameStartedText = document.createElement('div');
          gameStartedText.classList.add('game-started');
          gameStartedText.textContent = '游戏已开始';
          tableDiv.appendChild(gameStartedText);
        }

        tablesDiv.appendChild(tableDiv);
      });
    }

    function convertImageToBase64(url) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = 'Anonymous';
        img.onload = () => {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          canvas.width = img.width;
          canvas.height = img.height;
          ctx.drawImage(img, 0, 0);
          const dataURL = canvas.toDataURL('image/jpeg');
          resolve(dataURL);
        };
        img.onerror = reject;
        img.src = url;
      });
    }

    async function joinSeat(tableIndex, seatIndex) {
      const playerName = document.getElementById('player-name').value;
      if (!playerName) {
        alert('请输入玩家姓名');
        return;
      }
      // const avatarUrl = 'https://picsum.photos/64/64';
      // const avatarBase64 = await convertImageToBase64(avatarUrl);
      fetch('http://localhost:3000/join', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          player: {
            name: playerName
          },
          table: tableIndex,
          seat: seatIndex
        })
      })
        .then(response => response.json())
        .then(data => {
          if (data.error) {
            alert(data.error);
          } else {
            renderTables(data.tables);
          }
        });
    }

    async function login() {
      const playerName = document.getElementById('player-name').value;
      if (!playerName) {
        alert('请输入玩家姓名');
        return;
      }
      const avatarUrl = 'https://picsum.photos/64/64';
      const avatarBase64 = await convertImageToBase64(avatarUrl);
      fetch('http://localhost:3000/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          player: {
            name: playerName,
            avatar: avatarBase64
          }
        })
      })
        .then(response => response.json())
        .then(data => {
          if (data.error) {
            alert(data.error);
          } else {
            renderTables(data.tables);
          }
        });
    }

    document.getElementById('login-button').addEventListener('click', login);

    // 初始加载
    fetch('http://localhost:3000/tables')
      .then(response => response.json())
      .then(data => {
        renderTables(data.tables);
      });

    // 处理 WebSocket 消息
    socket.addEventListener('message', (event) => {
      const data = JSON.parse(event.data);
      renderTables(data.tables);
    });
  </script>
</body>

</html>